
<template>
  <div class="register">
    <a-divider>用户注册</a-divider>
    <a-form 
    :label-col="{ span: 4 }" 
    :wrapper-col="{ span: 16 }" 
    :rules="rules" 
    :model="user" 
    autocomplete="off"
    ref="formRef"
  >
      <a-form-item label="邮箱" name="account" has-feedback>
        <a-input v-model:value="user.account" type="email" autocomplete="off"/>
      </a-form-item>
      <a-form-item label="设置密码" name="password" has-feedback>
        <a-input-password v-model:value="user.password" type="password" autocomplete="off"/>
      </a-form-item>
      <a-form-item label="确认密码" name="confirmPassword" has-feedback>
        <a-input-password v-model:value="user.confirmPassword" type="password" autocomplete="off"/>
      </a-form-item>
      <a-form-item label="邮箱验证码" name="emailCode" >
        <a-input v-model:value.trim="user.emailCode" autocomplete="off" :disabled="flag"/>
        <a-button class="emailCodeBtn" @click="getEmailCode({addAddress:user.account})" :disabled="flag"
          >获取邮箱验证码</a-button
        >
      </a-form-item>
      <div>
        <a-button
          type="primary"
          html-type="submit"
          @click="showModal"
          :disabled="flagAll"
          >注册
        </a-button>
        <a-modal
          v-model:visible="visible"
          title="图形验证码"
          :confirm-loading="confirmLoading"
          @ok="handleOk(user)"
          cancelText='取消'
          okText='确认'
        >
        <a-row>
          <a-col :span="18" :push="6">   
            <a-input v-model:value.trim="user.code" class="codeImg" autocomplete="off"/>
          </a-col>
          <a-col :span="6" :pull="18">     
            <img :src="codeImg" alt="" @click="getCodeImg" />
          </a-col>
        </a-row>
        </a-modal>
      </div>      

    </a-form>
  </div>
</template>
<script>
import { _rules,loading,success,warning } from '@/antd';
import { EmailCode, userRegister } from "@/api/commonApi";
import { defineComponent, reactive, ref , onMounted , computed } from "vue"; 
import { useRouter } from 'vue-router';

export default defineComponent({
  name:'Register',
  setup() {
    onMounted(() => {
      setInterval(() => {
        getCodeImg()
      }, 120000);
    });
    let flag = computed(()=>{
      return !_rules.account.test(user.account);
    });
    let flagAll = computed(()=>{
      return !(_rules.account.test(user.account)&&_rules.password.test(user.password)&&(user.password===user.confirmPassword)&&(user.emailCode!==''));
    });
    const formRef = ref();
    const visible = ref(false);
    const confirmLoading = ref(false);
    let codeImg = ref(
      "https://www.semei.net/BookApi/Sms/Sms.php?s=imgCodeShow"
    );
    const user = reactive({
      account: "",
      password: "",
      confirmPassword:"",
      emailCode: "",
      code: "",
    });
    const router=useRouter()

    const getCodeImg = ()=>{
      codeImg.value =`https://www.semei.net/BookApi/Sms/Sms.php?s=imgCodeShow&timestamp=${+new Date()}`;
    };
    const getEmailCode = params => {
      EmailCode(params).then(data=>{
        console.log(data);
        loading('邮箱发送中…')
        setTimeout(() => {
          success('发送成功')
        }, 1000);
      }).catch(err=>warning(err));
    };
    let validatorPassword = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('密码不能为空！');
      } else {
        if(_rules.password.test(value)) {
          if (user.confirmPassword !== '') {
            formRef.value.validateFields('confirmPassword');
          }
          return Promise.resolve()
        } else return Promise.reject(_rules.password.message);
      }
    };
    let validatorConfirmPassword = async (_rule,value)=> {
      if (value === '') {
        return Promise.reject('请再次输入密码！');
      } else if (value !== user.password) {
        console.log(value);
        return Promise.reject("两次密码不一致！");
      } else {
        return Promise.resolve();
      }
    }
    const rules = {
      account: [{ required: true , validator:_rules.account.validator , trigger: 'change' }],
      password: [{ required: true , trigger: 'change' , validator:validatorPassword}],
      confirmPassword:[{ required: true  , validator:validatorConfirmPassword, trigger: 'change' }],
      emailCode:[{ required: true , message: _rules.emailCode.message , trigger: 'change' }]
    };


    const showModal = () => {
      visible.value = true;
    };
    const handleOk = data => {
      userRegister(data).then(()=>{
          setTimeout(() => {
            success('注册成功');
            router.push({ name: 'Login'})
          }, 1000)
        }).catch(err=>warning(err))
      confirmLoading.value = true;
      setTimeout(() => {
        visible.value = false;
        confirmLoading.value = false;
      }, 1000);
    };

    return {
      router,
      formRef,
      flag,
      flagAll,
      rules,
      user,
      codeImg,
      getCodeImg,
      getEmailCode,
      visible,
      confirmLoading,
      showModal,
      handleOk,
    };
  },

});


// export default {
//   name: "Register",
//   data() {
//     return {
//       user: { email: "", password: "", emailCode: "", code: "" },
//       codeImg: "https://www.semei.net/BookApi/Sms/Sms.php?s=imgCodeShow",
//     };
//   },
//   methods: {
//     getCodeImg() {
//       this.codeImg = `https://www.semei.net/BookApi/Sms/Sms.php?s=imgCodeShow&timestamp=${+new Date()}`;
//     },
//     getEmailCode,
//     register,
//   },
// };
</script>
<style lang="scss" scoped>
.register {
  width: 500px;
  margin: 0 auto;
  #emailCode {
    width:64%;
    margin-right: 10px;
  }
  #code {
    width:73%;
  }
  .emailCodeBtn {
    padding: 5px;
  }
  img {
    position: relative;
    top: -1px;
    margin-left: 10px;
    height: 32px;
  }
  .ant-btn.ant-btn-primary{
    position: relative;
    left: 50%;
    transform: translateX(-50%)
  }
}
  .codeImg{
    height: 100%;
  }
</style>